package educar.controllers;


import educar.gui.IView;
import educar.gui.admin.EditUser;
import educar.idioma.Locale;
import educar.models.User;


/**
 * Permite editar un usuario
 */
public class EditUserController implements IController {
	private EditUser view;
	private User oldUser;
	
	/**
	 * Constructor
	 * @param old User a editar
	 */
	public EditUserController(User old) {
		oldUser = old;
	}


	public void process(String model){
		if(null!=view) {
			/*obtiene los datos de la vista y comprueba validez*/
			String newName = view.getUsername();
			String newPassword = view.getPassword();
			String role = view.getRole();
			if(newName.length()==0 || newPassword.length()==0 || role.length()==0) {
				view.presentWarning(Locale.EMPTY_FIELDS, Locale.ERROR);
			}
			else {
				/*setea los nuevos datos y actualiza*/
				oldUser.setPassword(newPassword);
				oldUser.setRole(role);
				oldUser.setUsername(newName);
				boolean result = oldUser.update();
				if (!result) {
					view.presentWarning(Locale.USER_EXIST,Locale.ERROR);
				}
				else {
					view.present(Locale.USERS+" "+Locale.SAVED);
					view.close();	
				}				
			}
		}		
	}
	
	
	public void setView(IView view) {
		this.view = (EditUser) view;	
	}
}
